﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Generic;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Admin.Models.ConfigManager;
using Zocono.WCS.Admin.Models.User;
using Zocono.WCS.Application.AppConfigureManage;
using Zocono.WCS.Application.AppTraces;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoWcsManage;
using System.Linq;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;
using Zocono.WCS.Admin.Common;

namespace Zocono.WCS.Admin.Controllers.ConfigManageMoudle
{
    [BasicAuth]
    public class PlcPointInfoController : BaseController
    {
        private readonly PlcPointInfoApp _PlcPointInfoApp;
        private readonly PlcConnectionInfoApp _plcConnectionInfoApp;
        public PlcPointInfoController(IMemoryCache memoryCache, TracesApp tracesApp, IHttpContextAccessor httpContextAccessor, PlcPointInfoApp plcPointInfoApp,PlcConnectionInfoApp plcConnectionInfoApp) : base(memoryCache, tracesApp, httpContextAccessor)
        {
            _PlcPointInfoApp = plcPointInfoApp;
            _plcConnectionInfoApp = plcConnectionInfoApp;
        }

        public IActionResult Index()
        {
            return View();
        }

        
        public async Task<JsonResult> GetAllPlcPointInfoAsync()
        {
            var where = new QueryPlcPointDto();
            where.PageIndex = (Start / Length) + 1;
            where.PageSize = Length;
            where.Floor = Request.Form["floor"].ToInt32();
            where.ElevatorCode = Request.Form["ElevatorCode"].ToString();
            where.PlcConnectID = Request.Form["plcConnectID"].ToInt64();
            var plcPoints = await _PlcPointInfoApp.GetPagedPlcPointInfoAsync(where);

            var pageData = new TableData<PlcPointInfoDto>(Draw, plcPoints.Total, plcPoints.Total, plcPoints.Result);
            return Json(pageData);
        }




        /// <summary>
        /// 封装用于下拉列表的数据
        /// </summary>
        /// <returns></returns>
        public async Task<PlcPointInfoSearchPageData> GetPlcSearchDataAsync()
        {
            var plcPageSearchData = new PlcPointInfoSearchPageData();
            //通过 IP 去搜索
            var plcIps = await _plcConnectionInfoApp.GetPlcConnectionInfoAsync();
            plcPageSearchData.PlcIpSearchs = new List<PlcIPSearchPageData>();
            if (plcIps != null && plcIps.Count > 0)
            {
                foreach (var plcIp in plcIps)
                {
                    plcPageSearchData.PlcIpSearchs.Add(new PlcIPSearchPageData() { PlcConnectId = plcIp.ID.ToString(), PlcConnectIp = plcIp.IP });
                }
            }
            return plcPageSearchData;
        }

        /// <summary>
        /// plc点位配置页面
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> PlcPointInfoAsync()
        {
            var pagePlcPointData = await GetPlcSearchDataAsync();
            //await AddTracesInfo();
            return View(pagePlcPointData);
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PlcPointInfoAddOrEditAsync(long id)
        {
            var plcPointInfoDto = await GetPlcSearchDataAsync();

            if (id != 0)
            {
                var point = await _PlcPointInfoApp.GetPlcPointInfoByIdAsync(id);
                if (point != null)
                {
                    plcPointInfoDto.ID = point.ID;
                    plcPointInfoDto.Floor = point.Floor;
                    plcPointInfoDto.ElevatorCode = point.ElevatorCode;
                    plcPointInfoDto.PlcConnectID = point.PlcConnectID;
                    plcPointInfoDto.CrossroadCode = point.CrossroadCode;
                    plcPointInfoDto.ItemName = point.ItemName;
                    plcPointInfoDto.ItemValue = point.ItemValue;
                    plcPointInfoDto.Address = point.Address;
                    plcPointInfoDto.DataType = point.DataType;
                }
            }

            return View(plcPointInfoDto);
        }


        public async Task<ActionResult> OperatePlcPointInfoAsync()
        {
            var plcPointInfoDto = new PlcPointInfoDto
            {
                ID = Request.Form["id"].ToInt64(),
                Floor = Request.Form["Floor"].ToInt32(),
                ElevatorCode = Request.Form["ElevatorCode"].ToString(),
                PlcConnectID = Request.Form["PlcConnectionId"].ToInt64(),
                CrossroadCode = Request.Form["CrossroadCode"].ToString(),
                ItemName = Request.Form["ItemName"].ToString(),
                ItemValue = Request.Form["ItemValue"].ToString(),
                Address = Request.Form["Address"].ToString(),
                DataType = Request.Form["DataType"].ToString()
            };

            bool res=false;
            string msg=string.Empty;
            try
            {
                if (plcPointInfoDto.ID == 0)
                {
                    res = await _PlcPointInfoApp.InsertPlcPointInfoAsync(plcPointInfoDto);
                    await AddTracesInfo(2, 0, "新增PLC点位配置");
                }
                else
                {
                    res = await _PlcPointInfoApp.UpdatePlcPointInfoAsync(plcPointInfoDto);
                    await AddTracesInfo(3, 0, "修改PLC点位配置");
                }
                msg = res ? "成功" : "失败";
            }
            catch (System.Exception ex)
            {
                res = false;
                msg = "失败:" + ex.Message;
            }
            return CreateJsonGetResult(res, msg);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> DelPlcPointInfoByIdAsync()
        {
            var id = Request.Form["id"].ToInt64();
            bool res;
            string msg;
            try
            {
                res = await _PlcPointInfoApp.DeletePlcPointInfoByIdAsync(id);
                msg = res ? "成功" : "失败";
            }
            catch (System.Exception ex)
            {
                res = false;
                msg = "失败:" + ex.Message;
            }
            await AddTracesInfo(4, 0, "删除PLC点位配置");
            return CreateJsonGetResult(res, msg);
        }

    }
}
